package com.bw.demo;

import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TimestampInterceptor implements Interceptor {
    //列表缓存处理后的事件
    private ArrayList<Event> events = new  ArrayList<>();
    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        //从事件中获取元数据
        Map<String, String> headers = event.getHeaders();
        byte[] body = event.getBody();
        String s = new String(body);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String ts = jsonObject.getString("ts");
        headers.put("timestamp", ts);
        return event;

    }

    @Override
    public List<Event> intercept(List<Event> list) {
        events.clear();
        //批量处理事件列表
        for (Event event : list) {
            events.add(intercept(event));
        }
        return events;
    }

    @Override
    public void close() {

    }
    public static class Builder implements Interceptor.Builder {

        @Override
        public Interceptor build() {
            return new TimestampInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
